﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Tuzzit.GeocodeService;
using Microsoft.Phone.Controls.Maps;
using System.IO;

namespace Tuzzit
{
    public partial class NewAccount : PhoneApplicationPage
    {
        //Variables
        public GeocodeServiceClient geocodeService { get; set; }
        public GeocodeRequest geocodeReq { get; set; }
        public double Latitude { get; set; }
        public double Longitude { get; set; }
        public String prenom { get; set; }
        public String nom { get; set; }
        public String address { get; set; }
        public String mail { get; set; }
        public String pwd { get; set; }
        public String birthdate { get; set; }
        public int jour { get; set; }
        public int mois { get; set; }
        public int annee { get; set; }
        public bool conditions { get; set; }
        private bool _estNouvelleInstance = false;

        public NewAccount()
        {
            InitializeComponent();
            _estNouvelleInstance = true;
            PageTitle.Text = AppResources.NewAccount;
            FirstNameId.Text = AppResources.PrenomField;
            LastnameId.Text = AppResources.NomField;
            AddressId.Text = AppResources.AdresseField;
            PwdId.Text = AppResources.LabelPwd;
            TermConditions.Content = AppResources.TermsLink;
        }

        private void TermConditions_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Terms.xaml", UriKind.RelativeOrAbsolute));
        }

        private void PasswordStrategy_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/InfoPwd.xaml", UriKind.RelativeOrAbsolute));
        }

        private void msgCreate(object sender, RoutedEventArgs e)
        {
            //On récupère les variables
            prenom = FirstNameId.Text;
            nom = LastnameId.Text;
            mail = MailId.Text;
            address = AddressId.Text;
            pwd = passwordField.Password;        
            birthdate = datePicker.Value.ToString();
            jour = datePicker.Value.Value.Day;
            mois = datePicker.Value.Value.Month;
            annee = datePicker.Value.Value.Year;
            conditions = (bool)Terms.IsChecked;
            int cpterror = 0;

            //Verification des champs
            if (prenom.Equals(""))
            {
                FirstNameId.BorderBrush = new SolidColorBrush(Colors.Red);
                cpterror++;
            }

            if (nom.Equals("")) 
            {
                LastnameId.BorderBrush = new SolidColorBrush(Colors.Red);
                cpterror++;
            }

            if(mail.Equals(""))
            {
                MailId.BorderBrush = new SolidColorBrush(Colors.Red);
                cpterror++;
            }

            if(address.Equals(""))
            {
                AddressId.BorderBrush = new SolidColorBrush(Colors.Red);
                cpterror++;
            }

            if(pwd.Equals(""))
            {
                passwordField.BorderBrush = new SolidColorBrush(Colors.Red);
                cpterror++;
            }

            if(Terms.IsChecked != true)
            {
                TermConditions.Foreground = new SolidColorBrush(Colors.Red);
                cpterror++;
            }

            if (cpterror != 0)
            {
                MessageBox.Show("nbError: "+ cpterror +". Vérifier vos informations !");
            }
            else
            {
                //On recupère la localisation
                //On instancie le service
                geocodeService = new GeocodeServiceClient("BasicHttpBinding_IGeocodeService");
                geocodeService.GeocodeCompleted += geocodeService_GeocodeCompleted;

                //On instancie la requête
                geocodeReq = new GeocodeRequest();
                geocodeReq.Credentials = new Credentials() { ApplicationId = "AgXCIYxajlJXsSGnBvEFcS0QBUyWyxppoTy7xrIqun-D3_A0p2F8qiDJOo8xEr-3" };

                //On lance la recherche
                geocodeReq.Query = AddressId.Text;
                geocodeService.GeocodeAsync(geocodeReq);
            }
        }

        private void geocodeService_GeocodeCompleted(object sender, GeocodeCompletedEventArgs e)
        {
            if (e.Result != null && e.Result.Results.Any(x => x.Locations != null && x.Locations.Any()))
            {
                GeocodeResponse geocodeResponse = e.Result;
                Latitude = geocodeResponse.Results[0].Locations[0].Latitude;
                Longitude = geocodeResponse.Results[0].Locations[0].Longitude;
                createTuzzerAccount(Latitude, Longitude, prenom, nom, mail, address, pwd, birthdate, jour, mois, annee, conditions);
            }
            else
            {
                MessageBox.Show("Impossible de vous localiser");
                AddressId.BorderBrush = new SolidColorBrush(Colors.Red);
            }
        }

        private void createTuzzerAccount(double latitude, double longitude, string firstname, string lastname, string email, string adresse, string password, string birthday, int jour, int mois, int annnee, bool conditions)
        {
            string condTerm = "off";
            if (conditions == true) 
            {
                condTerm = "on";
            }
            MessageBox.Show("Latitude : " + latitude + "\nLongitude : " + longitude + "\nPrenom : " + firstname + "\nNom : " + lastname + "\nEmail : " + email + "\nAdresse : " + adresse + "\nPassword : " + password + "\nDate de naissance : " + birthday + "\nJour : " + jour + "\nMois : " + mois + "\nAnnee : " + annee + "\nConditions : " + condTerm);

            //Requete http au serveur
            //HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://dev.tuzzit.com/exec/new_user.php?name=" + lastname + "&firstname=" + firstname + "&email=" + email + "&city=" + adresse + "&password=" + password + "&confpassword=" + password + "&birthday_day=" + jour + "&birthday_month=" + mois + "&birthday_year=" + annee + "&agree=" + condTerm + "&lat=" + latitude + "&long=" + longitude);
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://dev.tuzzit.com/exec/new_user.php?name=" + lastname + "&firstname=" + firstname + "&email=" + email + "&city=" + adresse + "&password=" + password + "&confpassword=" + password + "&birthday_day=-1&birthday_month=-1&birthday_year=-1&agree=" + condTerm + "&lat=" + latitude + "&long=" + longitude);
           
            request.BeginGetResponse(new AsyncCallback(CreateAccountCallback), request);
        }

        private void CreateAccountCallback(IAsyncResult callbackResult)
        {
            HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
            HttpWebResponse myResponse = (HttpWebResponse)myRequest.EndGetResponse(callbackResult);

            using (StreamReader httpwebStreamReader = new StreamReader(myResponse.GetResponseStream()))
            {
                string results = httpwebStreamReader.ReadToEnd();
                //MessageBox.Show(results.ToString() //-- on another thread!
                Dispatcher.BeginInvoke(() => account_success(results.Trim()));
            }
            myResponse.Close();
        }

        private void account_success(string res)
        {
            MessageBox.Show(res);
            NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.RelativeOrAbsolute));
        }


        //Correction des champs
        private void RemoveBorderName(object sender, System.Windows.Input.GestureEventArgs e)
        {
            FirstNameId.BorderBrush = new SolidColorBrush(Colors.Transparent);
        }

        private void RemoveBorderLastname(object sender, System.Windows.Input.GestureEventArgs e)
        {
            LastnameId.BorderBrush = new SolidColorBrush(Colors.Transparent);
        }

        private void RemoveBorderMail(object sender, System.Windows.Input.GestureEventArgs e)
        {
            MailId.BorderBrush = new SolidColorBrush(Colors.Transparent);
        }

        private void RemoveBorderAddress(object sender, System.Windows.Input.GestureEventArgs e)
        {
            AddressId.BorderBrush = new SolidColorBrush(Colors.Transparent);
        }

        private void RemoveBorderPwd(object sender, System.Windows.Input.GestureEventArgs e)
        {
            passwordField.BorderBrush = new SolidColorBrush(Colors.Transparent);
        }

        private void RemoveColorLink(object sender, RoutedEventArgs e)
        {
            TermConditions.Foreground = new SolidColorBrush(Colors.White);
        }

        // Tombstoning

       protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (e.NavigationMode != System.Windows.Navigation.NavigationMode.Back)
            {
                // l'appli est désactivée, la page est quittée
                State["FirstNameId"] = FirstNameId.Text;
                State["LastnameId"] = LastnameId.Text;
                State["MailId"] = MailId.Text;
                State["AddressId"] = AddressId.Text;
                State["passwordField"] = passwordField.Password;
                State["datePicker"] = datePicker.Value;
            }
            else
            {
                // on quitte l'appli en appuyant sur back
            }
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (_estNouvelleInstance)
            {
                if (State.Count > 0)
                {
                    // application a été désactivée par l'OS, on peut accéder au dictionnaire d'état pour restaurer les infos
                    FirstNameId.Text = (string)State["FirstNameId"];
                    LastnameId.Text =  (string)State["LastnameId"];
                    MailId.Text = (string)State["MailId"];
                    AddressId.Text = (string)State["AddressId"];
                    passwordField.Password = (string)State["passwordField"];
                    datePicker.Value = (DateTime)State["datePicker"];
                }
                else
                {
                    // équivalent à un démarrage de l'appli
                }
            }
            else
            {
                // la page est gardée en mémoire, pas besoin d'aller lire le dictionnaire d'état
            }
            _estNouvelleInstance = false;
        }

    }
}